import { PageWarpperContext } from "@/src/components/page-warpper"
import Api from "@/src/lib/api/api"
import Global from "@/src/lib/global"
import CheckModel from "@/src/lib/models/check_model"
import { ITouchEvent, View } from "@tarojs/components"
import { useContext } from "react"
import Taro from '@tarojs/taro'
import "./index.scss"


interface NewUserPopupProps {
    model: CheckModel
    closeCallback: () => void
}


const NewUserPopup = (props: NewUserPopupProps) => {

    const { model } = props
    const ctx = useContext(PageWarpperContext)


    let requestGetCoupon = () => {
        Taro.showLoading()
        Api.goodsCouponGet({
            id: model.coupon_id
        }).then( res => {
            Taro.hideLoading()
            if (!Api.handleResponse(res)) {
                return
            }
            Global.showToast("领取成功")
            props.closeCallback()
        }).catch( err => {
            Taro.hideLoading()
            console.log(err)
        })
    }


    let onClick = () => {
        props.closeCallback()
    }

    let onWarpClick = (e: ITouchEvent<any>) => {
        e.stopPropagation()
        e.preventDefault()
    }

    let onGetBtnClick = () => {

        if (!Global.isLogin()) {
            let c = ctx.loginCompentRef?.current
            if (c) {
                c.loginCallback = (isOk) => {
                    if (isOk) {
                        requestGetCoupon()
                    }
                }
            }
            c?.show()
            return
        }

        requestGetCoupon()
    }

    return (
        <View className="new-user-popup" onClick={ onClick }>
            <View className="new-user-popup-warp" onClick={ onWarpClick }>
                <View className="new-user-popup-desc">
                    <View className="desc1">立减{Number.parseInt(model.coupon_price).toFixed(0)}元</View>
                    <View className="desc2">{ model.coupon_tip }</View>
                </View>
                <View className="new-user-popup-btn" onClick={ onGetBtnClick }>立即领取</View>
            </View>
        </View>
    )
}

export default NewUserPopup